import 'dart:io';

import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:dmz/base/controller/base_controller.dart';
import 'package:dmz/business/home/controller/home_main_controller.dart';
import 'package:dmz/business/home/model/moto_model.dart';
import 'package:dmz/business/home/model/serve_point.dart';
import 'package:dmz/business/home/widgets/map_widgets.dart';
import 'package:dmz/request/apis.dart';
import 'package:dmz/request/request_client.dart';
import 'package:dmz/tools/map/map_manger.dart';
import 'package:dmz/utils/customize_loding.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

class MapServePointController extends BaseController {
  @override
  void loadNet() {}

  @override
  void onHidden() {}

  late MotoModel data;
  LatLng? initLatLng; //初始化车辆位置
  Map<String, Marker> markerMap = {}; //标记点
  late AMapController mapController;
  List<ServePoint>? pointList;
  ServePoint? selectPoint;
  bool showAppSelect = false;

  @override
  void onInit() {
    var controllered = Get.find<HomePageController>();
    data = controllered.motoList[controllered.pageIndex];
    getMotoLocation();
    super.onInit();
  }

  ///获取车辆位置
  getMotoLocation() {
    RequestClient().post<Map<String, dynamic>>(APIS.getMotoMsg,
        data: {'ebike_id': data.id, 'cmd': 'Location'}).then((value) async {
      var latLng =
          await EMIMapManger().convertLatLng(value?['lng'], value?['lat']);
      // initLatLng = latLng;
      addMarkerMap(latLng, 'moto');
      getServePointLocation(latLng);
    });
  }

  ///获取网点位置
  getServePointLocation(LatLng latLng) {
    RequestClient().post<ServePointData>(APIS.servePoint, data: {
      'lat': latLng.latitude,
      'lng': latLng.longitude
    }).then((value) async {
      if (value != null) {
        pointList = [];
        double? speed0;
        for (var i = 0; i < value.list!.length; i++) {
          var element = value.list![i];
          if ((element.coordinate?.lng ?? 0) > 0) {
            pointList?.add(element);
            var speed = EMIMapManger().calculateDistance(
                latLng.latitude,
                latLng.longitude,
                element.coordinate?.lat ?? 0,
                element.coordinate?.lng ?? 0);
            if (speed0 == null) {
              speed0 = speed;
              selectPoint = element;
            } else if (speed < speed0) {
              speed0 = speed;
              selectPoint = element;
            }
          }
        }
      }
      if (selectPoint != null) {
        var latLnged = await EMIMapManger().convertLatLng(
            selectPoint!.coordinate!.lng!, selectPoint!.coordinate!.lat!);
        initLatLng = latLnged;
        addMarkerMap(latLnged, 'sever');
      }
      debugPrint('获取网点位置 -- ${selectPoint?.name ?? ''}');
    });
  }

  ///添加大头针
  addMarkerMap(LatLng latLng, String key, {bool isClean = false}) {
    if (isClean) markerMap.clear();
    var iconed = BitmapDescriptor.fromIconPath(key == 'sever'
        ? 'assets/gif/location.gif'
        : 'assets/images/home/main/location_image.png');
    Marker marker = Marker(position: latLng, icon: iconed);
    markerMap[key] = marker;
    update();
  }

  seleMapApp() {
    showAppSelect = true;
    update();
    EMILoding.showBottomWindow(
        MapWidgets.seleMapAppWidget((type) {
          type == 0
              ? launchAmapApp(initLatLng!)
              : launchBaiduMapApp(selectPoint?.addr ?? '');
        }),
        isDismissible: false,
        close: () {
          showAppSelect = false;
          update();
        });
  }

  // 打开百度地图App
  void launchBaiduMapApp(String address) async {
    // String url =
    //     'baidumap://map/direction?destination=${latLng.latitude},${latLng.longitude}';
    String url = 'baidumap://map/direction?destination=$address';
    try {
      await launchUrl(Uri.parse(url));
    } catch (e) {
      EMILoding.hitLoding('请安装百度地图App'.tr);
    }
  }

  // 打开高德地图App并定位到指定位置
  void launchAmapApp(LatLng latLng) async {
    String url =
        '${Platform.isIOS ? 'iosamap' : 'androidamap'}://openFeature?featureName=OnRideNavi&rideType=elebike&sourceApplication=appname';

    // 构建完整的Scheme URL
    String fullUrl =
        '$url&lat=${latLng.latitude}&lon=${latLng.longitude}&dev=0';
    launchUrl(Uri.parse(fullUrl)).then((value) {
      if (!value) {
        EMILoding.hitLoding('请安装高德地图App'.tr);
      }
    });
  }
}
